﻿using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// DAC设置窗口
    /// 支持-9.99V到+9.99V的电压输出设置
    /// </summary>
    public partial class DACSettingsForm : UIForm
    {
        #region 控件声明
        private UIGroupBox groupBoxVoltageSet;
        private UITextBox txtVoltage;
        private UILabel lblVoltage;
        private UILabel lblVoltageUnit;
        private UILabel lblVoltageRange;
        private UIButton btnSetVoltage;
        private UIButton btnZeroCalibration;
        private UIButton btnCancel;

        private UIGroupBox groupBoxCurrentStatus;
        private UILabel lblCurrentVoltage;
        private UILabel lblCurrentStatus;
        private UILabel lblLastSetTime;

        private UIGroupBox groupBoxPresetValues;
        private UIButton btnPreset1;
        private UIButton btnPreset2;
        private UIButton btnPreset3;
        private UIButton btnPreset4;
        private UIButton btnPreset5;
        private UIButton btnPreset6;
        #endregion

        #region 字段
        private UdpProtocolSender udpSender;
        private double currentVoltage;
        private DateTime lastSetTime = DateTime.MinValue;
        #endregion

        public DACSettingsForm(UdpProtocolSender udpSender)
        {
            this.udpSender = udpSender;
            InitializeComponent();
            InitializeSettings();

            // 添加Load事件处理
            this.Load += DACSettingsForm_Load;
        }

        private void DACSettingsForm_Load(object sender, EventArgs e)
        {
            // 在窗口完全加载后再次加载DAC设置
            LoadDACSettings();
        }

        #region 初始化
        private void InitializeComponent()
        {
            this.groupBoxVoltageSet = new UIGroupBox();
            this.txtVoltage = new UITextBox();
            this.lblVoltage = new UILabel();
            this.lblVoltageUnit = new UILabel();
            this.lblVoltageRange = new UILabel();
            this.btnSetVoltage = new UIButton();
            this.btnZeroCalibration = new UIButton();
            this.btnCancel = new UIButton();

            this.groupBoxCurrentStatus = new UIGroupBox();
            this.lblCurrentVoltage = new UILabel();
            this.lblCurrentStatus = new UILabel();
            this.lblLastSetTime = new UILabel();

            this.groupBoxPresetValues = new UIGroupBox();
            this.btnPreset1 = new UIButton();
            this.btnPreset2 = new UIButton();
            this.btnPreset3 = new UIButton();
            this.btnPreset4 = new UIButton();
            this.btnPreset5 = new UIButton();
            this.btnPreset6 = new UIButton();

            this.SuspendLayout();

            // Form属性
            this.Text = "DAC电压设置";
            this.Size = new Size(480, 420);
            this.StartPosition = FormStartPosition.CenterParent;
            this.ShowInTaskbar = false;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;

            // groupBoxVoltageSet
            this.groupBoxVoltageSet.Text = "电压设置";
            this.groupBoxVoltageSet.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            this.groupBoxVoltageSet.Location = new Point(15, 50);
            this.groupBoxVoltageSet.Size = new Size(430, 120);
            this.groupBoxVoltageSet.Controls.Add(this.lblVoltage);
            this.groupBoxVoltageSet.Controls.Add(this.txtVoltage);
            this.groupBoxVoltageSet.Controls.Add(this.lblVoltageUnit);
            this.groupBoxVoltageSet.Controls.Add(this.lblVoltageRange);
            this.groupBoxVoltageSet.Controls.Add(this.btnSetVoltage);
            this.groupBoxVoltageSet.Controls.Add(this.btnZeroCalibration);

            // lblVoltage
            this.lblVoltage.Text = "输出电压:";
            this.lblVoltage.Font = new Font("微软雅黑", 9F);
            this.lblVoltage.Location = new Point(15, 35);
            this.lblVoltage.AutoSize = true;

            // txtVoltage
            this.txtVoltage.Location = new Point(85, 32);
            this.txtVoltage.Size = new Size(100, 25);
            this.txtVoltage.Font = new Font("微软雅黑", 9F);
            this.txtVoltage.KeyPress += TxtVoltage_KeyPress;

            // lblVoltageUnit
            this.lblVoltageUnit.Text = "V";
            this.lblVoltageUnit.Font = new Font("微软雅黑", 9F);
            this.lblVoltageUnit.Location = new Point(195, 35);
            this.lblVoltageUnit.AutoSize = true;

            // lblVoltageRange
            this.lblVoltageRange.Text = "范围: -9.99V ~ +9.99V";
            this.lblVoltageRange.Font = new Font("微软雅黑", 8F);
            this.lblVoltageRange.ForeColor = Color.Gray;
            this.lblVoltageRange.Location = new Point(85, 60);
            this.lblVoltageRange.AutoSize = true;

            // btnSetVoltage
            this.btnSetVoltage.Text = "设置电压";
            this.btnSetVoltage.Location = new Point(260, 30);
            this.btnSetVoltage.Size = new Size(75, 30);
            this.btnSetVoltage.Font = new Font("微软雅黑", 9F);
            this.btnSetVoltage.FillColor = Color.FromArgb(80, 160, 255);
            this.btnSetVoltage.Click += BtnSetVoltage_Click;

            // btnZeroCalibration
            this.btnZeroCalibration.Text = "零点校准";
            this.btnZeroCalibration.Location = new Point(345, 30);
            this.btnZeroCalibration.Size = new Size(75, 30);
            this.btnZeroCalibration.Font = new Font("微软雅黑", 9F);
            this.btnZeroCalibration.FillColor = Color.FromArgb(255, 184, 0);
            this.btnZeroCalibration.Click += BtnZeroCalibration_Click;

            // groupBoxCurrentStatus
            this.groupBoxCurrentStatus.Text = "当前状态";
            this.groupBoxCurrentStatus.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            this.groupBoxCurrentStatus.Location = new Point(15, 180);
            this.groupBoxCurrentStatus.Size = new Size(430, 100);
            this.groupBoxCurrentStatus.Controls.Add(this.lblCurrentVoltage);
            this.groupBoxCurrentStatus.Controls.Add(this.lblCurrentStatus);
            this.groupBoxCurrentStatus.Controls.Add(this.lblLastSetTime);

            // lblCurrentVoltage
            this.lblCurrentVoltage.Text = "当前电压: 0.00V";
            this.lblCurrentVoltage.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            this.lblCurrentVoltage.Location = new Point(15, 30);
            this.lblCurrentVoltage.AutoSize = true;

            // lblCurrentStatus
            this.lblCurrentStatus.Text = "状态: 就绪";
            this.lblCurrentStatus.Font = new Font("微软雅黑", 9F);
            this.lblCurrentStatus.Location = new Point(15, 55);
            this.lblCurrentStatus.AutoSize = true;

            // lblLastSetTime
            this.lblLastSetTime.Text = "最后设置时间: 无";
            this.lblLastSetTime.Font = new Font("微软雅黑", 9F);
            this.lblLastSetTime.Location = new Point(220, 55);
            this.lblLastSetTime.AutoSize = true;

            // groupBoxPresetValues
            this.groupBoxPresetValues.Text = "预设值";
            this.groupBoxPresetValues.Font = new Font("微软雅黑", 10F, FontStyle.Bold);
            this.groupBoxPresetValues.Location = new Point(15, 290);
            this.groupBoxPresetValues.Size = new Size(430, 80);
            this.groupBoxPresetValues.Controls.Add(this.btnPreset1);
            this.groupBoxPresetValues.Controls.Add(this.btnPreset2);
            this.groupBoxPresetValues.Controls.Add(this.btnPreset3);
            this.groupBoxPresetValues.Controls.Add(this.btnPreset4);
            this.groupBoxPresetValues.Controls.Add(this.btnPreset5);
            this.groupBoxPresetValues.Controls.Add(this.btnPreset6);

            // 预设按钮配置
            SetupPresetButton(this.btnPreset1, "0.0V", new Point(15, 30), 0.0);
            SetupPresetButton(this.btnPreset2, "1.0V", new Point(85, 30), 1.0);
            SetupPresetButton(this.btnPreset3, "3.0V", new Point(155, 30), 3.0);
            SetupPresetButton(this.btnPreset4, "5.0V", new Point(225, 30), 5.0);
            SetupPresetButton(this.btnPreset5, "-3.0V", new Point(295, 30), -3.0);
            SetupPresetButton(this.btnPreset6, "9.0V", new Point(365, 30), 9.0);

            // btnCancel
            this.btnCancel.Text = "关闭";
            this.btnCancel.Location = new Point(370, 380);
            this.btnCancel.Size = new Size(75, 30);
            this.btnCancel.Font = new Font("微软雅黑", 9F);
            this.btnCancel.FillColor = Color.FromArgb(160, 160, 160);
            this.btnCancel.Click += BtnCancel_Click;

            // 添加控件到窗体
            this.Controls.Add(this.groupBoxVoltageSet);
            this.Controls.Add(this.groupBoxCurrentStatus);
            this.Controls.Add(this.groupBoxPresetValues);
            this.Controls.Add(this.btnCancel);

            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private void SetupPresetButton(UIButton btn, string text, Point location, double voltage)
        {
            btn.Text = text;
            btn.Location = location;
            btn.Size = new Size(60, 30);
            btn.Font = new Font("微软雅黑", 8F);
            btn.FillColor = Color.FromArgb(220, 220, 220);
            btn.ForeColor = Color.Black;
            btn.Tag = voltage;
            btn.Click += PresetButton_Click;
        }

        private void InitializeSettings()
        {
            try
            {
                // 先加载DAC设置，不依赖UDP发送器
                LoadDACSettings();

                if (udpSender != null)
                {
                    // 订阅UDP发送器事件
                    udpSender.OnLogMessage += msg => ShowStatusMessage($"发送: {msg}");
                    udpSender.OnErrorMessage += err => ShowStatusMessage($"错误: {err}");
                }

                UpdateStatus("就绪");
            }
            catch (Exception ex)
            {
                ShowErrorMessage($"初始化失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从配置文件加载DAC设置
        /// </summary>
        private void LoadDACSettings()
        {
            try
            {
                currentVoltage = AppConfig.DACVoltage;
                txtVoltage.Text = currentVoltage.ToString("F2");

                // 直接更新显示，避免在构造函数阶段使用Invoke
                lblCurrentVoltage.Text = $"当前电压: {currentVoltage:F2}V";

                // 根据电压值设置颜色
                if (currentVoltage == 0)
                    lblCurrentVoltage.ForeColor = Color.Green;
                else if (currentVoltage > 0)
                    lblCurrentVoltage.ForeColor = Color.Blue;
                else
                    lblCurrentVoltage.ForeColor = Color.Red;
            }
            catch (Exception ex)
            {
                // 使用默认值
                currentVoltage = 0.0;
                txtVoltage.Text = "0.00";
                lblCurrentVoltage.Text = "当前电压: 0.00V";
                ShowErrorMessage($"加载DAC配置失败: {ex.Message}");
            }
        }
        #endregion

        #region 事件处理
        private void TxtVoltage_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 获取UITextBox实例
            UITextBox textBox = sender as UITextBox;
            if (textBox == null) return;

            // 允许数字、小数点、负号、退格和删除
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
                e.KeyChar != '.' && e.KeyChar != '-')
            {
                e.Handled = true;
                return;
            }

            // 只允许一个小数点
            if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1)
            {
                e.Handled = true;
                return;
            }

            // 负号只能在开头
            if (e.KeyChar == '-' && textBox.SelectionStart != 0)
            {
                e.Handled = true;
                return;
            }

            // 回车键触发设置
            if (e.KeyChar == (char)Keys.Enter)
            {
                BtnSetVoltage_Click(sender, e);
                e.Handled = true;
            }
        }

        private void BtnSetVoltage_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ValidateVoltageInput(out double voltage))
                    return;

                SetDACVoltage(voltage);
            }
            catch (Exception ex)
            {
                ShowErrorMessage($"设置电压异常: {ex.Message}");
                UpdateStatus("错误");
            }
        }

        private void BtnZeroCalibration_Click(object sender, EventArgs e)
        {
            try
            {
                SetDACVoltage(0.0);
                ShowSuccessMessage("零点校准完成");
            }
            catch (Exception ex)
            {
                ShowErrorMessage($"零点校准失败: {ex.Message}");
            }
        }

        private void PresetButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender is UIButton btn && btn.Tag is double voltage)
                {
                    txtVoltage.Text = voltage.ToString("F2");
                    ShowStatusMessage($"选择预设值: {voltage:F2}V");
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage($"预设值选择失败: {ex.Message}");
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region 业务逻辑
        private bool ValidateVoltageInput(out double voltage)
        {
            voltage = 0;

            if (string.IsNullOrWhiteSpace(txtVoltage.Text))
            {
                ShowWarningMessage("请输入电压值");
                txtVoltage.Focus();
                return false;
            }

            if (!double.TryParse(txtVoltage.Text, out voltage))
            {
                ShowWarningMessage("电压值格式不正确");
                txtVoltage.SelectAll();
                txtVoltage.Focus();
                return false;
            }

            if (Math.Abs(voltage) > 9.99)
            {
                ShowWarningMessage("电压值超出范围(-9.99V ~ +9.99V)");
                txtVoltage.SelectAll();
                txtVoltage.Focus();
                return false;
            }

            return true;
        }

        private void SetDACVoltage(double voltage)
        {
            try
            {
                if (udpSender == null)
                {
                    ShowErrorMessage("UDP发送器未初始化");
                    return;
                }

                UpdateStatus("设置中...");

                bool success = udpSender.SendDACSet(voltage);

                if (success)
                {
                    currentVoltage = voltage;
                    lastSetTime = DateTime.Now;

                    // 保存到配置文件
                    if (AppConfig.SaveDACSettings(voltage))
                    {
                        ShowStatusMessage("DAC配置已保存到文件");
                    }

                    UpdateCurrentVoltageDisplay();
                    UpdateLastSetTimeDisplay();
                    UpdateStatus("设置成功");

                    ShowSuccessMessage($"DAC电压设置成功: {voltage:F2}V");
                }
                else
                {
                    UpdateStatus("设置失败");
                    ShowErrorMessage("DAC电压设置失败");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus("异常");
                ShowErrorMessage($"DAC设置异常: {ex.Message}");
                throw;
            }
        }

        private void UpdateCurrentVoltageDisplay()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => {
                    lblCurrentVoltage.Text = $"当前电压: {currentVoltage:F2}V";
                    SetVoltageDisplayColor();
                }));
            }
            else
            {
                lblCurrentVoltage.Text = $"当前电压: {currentVoltage:F2}V";
                SetVoltageDisplayColor();
            }
        }

        private void SetVoltageDisplayColor()
        {
            if (currentVoltage == 0)
                lblCurrentVoltage.ForeColor = Color.Green;
            else if (currentVoltage > 0)
                lblCurrentVoltage.ForeColor = Color.Blue;
            else
                lblCurrentVoltage.ForeColor = Color.Red;
        }

        private void UpdateLastSetTimeDisplay()
        {
            this.Invoke(new Action(() => {
                lblLastSetTime.Text = $"最后设置: {lastSetTime:HH:mm:ss}";
            }));
        }

        private void UpdateStatus(string status)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => {
                    lblCurrentStatus.Text = $"状态: {status}";
                    SetStatusColor(status);
                }));
            }
            else
            {
                lblCurrentStatus.Text = $"状态: {status}";
                SetStatusColor(status);
            }
        }

        private void SetStatusColor(string status)
        {
            switch (status)
            {
                case "就绪":
                case "设置成功":
                    lblCurrentStatus.ForeColor = Color.Green;
                    break;
                case "设置中...":
                    lblCurrentStatus.ForeColor = Color.Orange;
                    break;
                case "设置失败":
                case "错误":
                case "异常":
                    lblCurrentStatus.ForeColor = Color.Red;
                    break;
                default:
                    lblCurrentStatus.ForeColor = Color.Black;
                    break;
            }
        }
        #endregion

        #region 消息提示
        private void ShowStatusMessage(string message)
        {
            // 在状态栏或通过其他方式显示状态消息
            UpdateStatus("就绪");
        }

        private void ShowSuccessMessage(string message)
        {
            MessageBox.Show(message, "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ShowWarningMessage(string message)
        {
            MessageBox.Show(message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void ShowErrorMessage(string message)
        {
            MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        #endregion

        #region 资源清理
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (disposing && udpSender != null)
                {
                    // 取消事件订阅
                    udpSender.OnLogMessage -= msg => ShowStatusMessage($"发送: {msg}");
                    udpSender.OnErrorMessage -= err => ShowStatusMessage($"错误: {err}");
                }
            }
            catch
            {
                // 忽略清理错误
            }

            base.Dispose(disposing);
        }
        #endregion
    }
}